<template>
  <el-container class="app-layout">
    <!-- 侧边栏 -->
    <el-aside :width="sidebarWidth" class="sidebar" :class="{ 'collapsed': sidebarCollapsed }">
      <div class="sidebar-header">
        <h2 class="logo" :class="{ 'collapsed': sidebarCollapsed }">云川数据平台</h2>
      </div>
      
      <el-menu
        :default-active="activeMenu"
        :collapse="sidebarCollapsed"
        :unique-opened="true"
        :collapse-transition="false"
        router
        class="sidebar-menu"
      >
        <el-menu-item index="/dashboard">
          <el-icon><DataBoard /></el-icon>
          <span>仪表板</span>
        </el-menu-item>
        
        <el-sub-menu index="/monitor">
          <template #title>
            <el-icon><Monitor /></el-icon>
            <span>数据监控</span>
          </template>
          <el-menu-item index="/monitor/overview">数据概览</el-menu-item>
          <el-menu-item index="/monitor/tables">数据列表</el-menu-item>
        </el-sub-menu>
        
        <el-sub-menu index="/flink">
          <template #title>
            <el-icon><Connection /></el-icon>
            <span>Flink作业</span>
          </template>
          <el-menu-item index="/flink/jobs">作业管理</el-menu-item>
          <el-menu-item index="/flink/mappings">作业映射</el-menu-item>
        </el-sub-menu>
        
        <el-menu-item index="/task-monitor">
          <el-icon><Clock /></el-icon>
          <span>异步任务</span>
        </el-menu-item>
        
        <el-sub-menu index="/alert">
          <template #title>
            <el-icon><Warning /></el-icon>
            <span>告警管理</span>
          </template>
          <el-menu-item index="/alert/rules">告警规则</el-menu-item>
          <el-menu-item index="/alert/history">告警历史</el-menu-item>
        </el-sub-menu>
        
        <el-sub-menu index="/report">
          <template #title>
            <el-icon><Document /></el-icon>
            <span>报表中心</span>
          </template>
          <el-menu-item index="/report/list">报表定义</el-menu-item>
          <el-menu-item index="/report/executions">执行历史</el-menu-item>
        </el-sub-menu>
        
        <el-sub-menu index="/system">
          <template #title>
            <el-icon><Setting /></el-icon>
            <span>系统管理</span>
          </template>
          <el-menu-item index="/system/configs">系统配置</el-menu-item>
          <el-menu-item index="/system/database">数据库配置</el-menu-item>
          <el-menu-item index="/system/wechat-bots">微信机器人</el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>
    
    <!-- 主内容区 -->
    <el-container>
      <!-- 顶部栏 -->
      <el-header class="header">
        <div class="header-left">
          <el-button
            type="text"
            @click="toggleSidebar"
            class="sidebar-toggle"
            :loading="toggleLoading"
          >
            <el-icon><Fold v-if="!sidebarCollapsed" /><Expand v-else /></el-icon>
          </el-button>
          
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item v-if="currentRoute.meta?.title">
              {{ currentRoute.meta.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <div class="header-right">
          <el-dropdown @command="handleUserCommand">
            <span class="user-info">
              <el-avatar :size="32" :src="userAvatar">
                {{ userInitials }}
              </el-avatar>
              <span class="username">{{ authStore.user?.username }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                <el-dropdown-item command="settings">设置</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      
      <!-- 内容区 -->
      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 侧边栏状态
const sidebarCollapsed = ref(false)
const toggleLoading = ref(false)

// 计算属性 - 使用缓存优化
const sidebarWidth = computed(() => sidebarCollapsed.value ? '64px' : '240px')
const activeMenu = computed(() => route.path)
const currentRoute = computed(() => route)

const userAvatar = computed(() => '')
const userInitials = computed(() => {
  const username = authStore.user?.username || ''
  return username.substring(0, 2).toUpperCase()
})

// 切换侧边栏 - 优化性能
const toggleSidebar = async () => {
  if (toggleLoading.value) return
  
  toggleLoading.value = true
  
  try {
    // 使用 nextTick 确保DOM更新完成
    await nextTick()
    
    // 使用 requestAnimationFrame 优化动画性能
    requestAnimationFrame(() => {
      sidebarCollapsed.value = !sidebarCollapsed.value
      
      // 延迟重置loading状态，避免频繁切换
      setTimeout(() => {
        toggleLoading.value = false
        // 合并触发一次全局resize，避免多图表各自重算引起的抖动
        if (typeof window !== 'undefined') {
          requestIdleCallback?.(() => window.dispatchEvent(new Event('resize')))
          // 再补发一次，确保异步布局稳定后的图表完成自适应
          setTimeout(() => window.dispatchEvent(new Event('resize')), 120)
          setTimeout(() => window.dispatchEvent(new Event('resize')), 240)
        }
      }, 300)
    })
  } catch (error) {
    toggleLoading.value = false
  }
}

// 处理用户菜单命令
const handleUserCommand = async (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await authStore.logout()
        router.push('/login')
      } catch {
        // 用户取消
      }
      break
  }
}
</script>

<style scoped>
.app-layout {
  height: 100vh;
}

.sidebar {
  background-color: #304156;
  /* 关闭width动画，避免大面积重排 */
  transition: none;
  overflow: hidden;
  /* 硬件加速优化 */
  will-change: width;
  transform: translateZ(0);
  backface-visibility: hidden;
  perspective: 1000px;
}

.sidebar.collapsed {
  /* 折叠状态优化 */
  transform: translateZ(0);
}

.sidebar-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2b3a4b;
  border-bottom: 1px solid #3a4b5c;
  /* 防止内容溢出 */
  overflow: hidden;
}

.logo {
  color: white;
  font-size: var(--font-title);
  font-weight: 600;
  margin: 0;
  white-space: nowrap;
  transition: opacity 0.3s ease;
}

.logo.collapsed {
  opacity: 0;
  /* 完全隐藏折叠状态的logo */
  visibility: hidden;
}

.sidebar-menu {
  border: none;
  background-color: #304156;
  /* 优化菜单渲染 */
  contain: layout style;
}

.sidebar-menu :deep(.el-menu-item),
.sidebar-menu :deep(.el-sub-menu__title) {
  color: #bfcbd9;
  background-color: #304156;
  /* 优化hover效果 */
  transition: all 0.2s ease;
}

.sidebar-menu :deep(.el-menu-item:hover),
.sidebar-menu :deep(.el-sub-menu__title:hover) {
  color: #409eff;
  background-color: #263445;
}

.sidebar-menu :deep(.el-menu-item.is-active) {
  color: #409eff;
  background-color: #263445;
}

.header {
  background-color: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  /* 防止重排 */
  contain: layout;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.sidebar-toggle {
  font-size: var(--font-size-18);
  color: #606266;
  /* 优化按钮点击 */
  transition: all 0.2s ease;
}

.sidebar-toggle:hover {
  color: #409eff;
  transform: scale(1.05);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.username {
  font-size: var(--font-body);
  color: #606266;
}

.main-content {
  background-color: #f5f5f5;
  padding: 20px;
  overflow-y: auto;
  /* 优化滚动性能 */
  -webkit-overflow-scrolling: touch;
  /* 收敛重排区域，减少侧栏切换影响 */
  contain: layout paint;
  will-change: contents;
}
</style> 